import { $authToken } from '@tourfly/api';
import { useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { removeToken } from '~/common/utils';
import { useAppDispatch, useAppSelector } from '~/store/hooks';
import { reset } from '~/store/profileSlice';
import { logout } from '~/store/user';

export default function useUser() {
  const { userInfo } = useAppSelector((store) => store.user);
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const handleLogout = useCallback(() => {
    dispatch(logout());
    removeToken();
    $authToken.set(undefined);
    dispatch(reset());
    navigate('/signin');
  }, [dispatch, navigate]);

  const memoUser = useMemo(() => userInfo, [userInfo]);
  return {
    userInfo: memoUser,
    handleLogout,
  };
}
